package com.hcmus.armobile;


import global.global;

import java.io.IOException;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.hcmus.arLocation.ArLocation;
import com.hcmus.armobile.R.id;
import com.hcmus.post2server.post2server;

import common.StoreType;
import common.SystemFunction;
import common.User;
import config.config;

import db.DBHandle;

import Server.ConvertData;
import Server.HandleServer;
import Server.Post;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {
	ImageButton btnArroundMe = null;
	ImageButton btnFavorite = null;
	private ImageButton btnAddCategoriesFavor;
	private ImageButton btnAddLocationFavor;
	AsyncTask<Void, Void, Void> mRegisterTask;
			
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.armobile);  
		
		
		
		//HandleServer.GetListStoreByChain(8);
		/*
		String s="ewoJInN0b3JldHlwZSI6IFsKCQl7CgkJCSJpZCI6ICIxIiwKCQkJIm5hbWUiOiAiTXVhIHNcdTFlYWZtIgoJCX0sCgkJewoJCQkiaWQiOiAiMiIsCgkJCSJuYW1lIjogIlx1MDEwMm4gdVx1MWVkMW5nIgoJCX0sCgkJewoJCQkiaWQiOiAiNCIsCgkJCSJuYW1lIjogIlZ1aSBjaFx1MDFhMWksIGdpXHUxZWEzaSB0clx1MDBlZCIKCQl9LAoJCXsKCQkJImlkIjogIjgiLAoJCQkibmFtZSI6ICJDXHUwMGY0bmcgTmdoXHUxZWM3IgoJCX0sCgkJewoJCQkiaWQiOiAiMTYiLAoJCQkibmFtZSI6ICJEdSBMXHUxZWNiY2giCgkJfQoJXQp9";
		JSONObject jsonData = Post.ParseString2JsonObject(s);
		ArrayList<StoreType> lst = Post.parseJSONStoreType(jsonData);
		boolean re = DBHandle.AddListStoreType(lst);
		int a = 5;
		a  = 7;
		ArrayList<StoreType> lsts = DBHandle.GetListStoreType();
		
		a = 7;
		*/
		/*get webserver*/ 
		 
		//SystemFunction sf = new SystemFunction();
		//sf.GetWebServer(getAssets());	
		 /*end get webserver*/ 
	/*	
		ArrayList<StoreType> lst = new ArrayList<StoreType>();
		
		lst = DBHandle.GetListStoreType();
		int a = 1;
		a = 2;*/
		
		/*lst.add(new StoreType(1,"Name 1"));
		lst.add(new StoreType(2,"Name 2"));
		lst.add(new StoreType(4,"Name 3"));
		lst.add(new StoreType(8,"Name 4"));
		
		DBHandle.AddListStoreType(lst);*/
		//DBHandle.CreateTablePromotionPush();
		//DBHandle.AddPromotionPush(1);
		//DBHandle.GetListPtomotionPush();
		
	//	HandleServer.GetListStoreNearPosition("10.214523", "106.321421", "100"); 
		//HandleServer.GetListStoreFavourite();
		//HandleServer.AddUpdateFavourite(1,"3",-1);
		//HandleServer.GetListPromotionSearch("", "439,440", 31, "1", "333333333");
		//HandleServer.GetListStoreSearch("", "439,440", 31);
		//HandleServer.GetListPromotionByStoreId(26);
		//DBHandle.GetListStore("select t1.*,t2.name as type_name,t3.name as district_name, t3.parent_name as city_name from ar_store t1 left join ar_store_type t2 on t1.type = t2.id left join ar_location t3 on t1.location_id = t3.id");
		
		//DBHandle.GetListPromotion("Select * from ar_promotion");
		
		/*Get info user*/
		
		//User u = new User(1,"APA91bGAFKgYOzfk1I0LkEq-0iOHkB5sChrqz9NOu9FVBJey2dGLYvR0dxYQPbTewapONq9O79jEa8cl-YsoG-Sa1upfl6NvF5XNCNc3c_PXpLzflO_DIqbgaphaptlVyHTEY89k2ZZ5s_JgPv2DteTH2IhpWmZMkw","Name","Email","23/4/2013",0,"");
		//boolean re = DBHandle.Use   rAdd(u);
		
		//GCMRegistrar.unregister(getApplicationContext());
		
		/*int kk = 1;  
        if(kk == 1){
	        final Context context = this;        
	        GCMRegistrar.unregister(context);  
        }*/
        
	//	HandleServer.GetListPromotionByStoreId(26);		
		if(global.curUser == null){
			User u =null;
			try{
				u = DBHandle.GetUser();
			}catch(Exception ex){
				
			}
			if(u != null){
				global.curUser = u;
				
			}else{// not register
				/*push notification*/		
				/// check account		
					try{
					
					AccountManager accountManager = AccountManager.get(getApplicationContext());
					Account[] accounts = accountManager.getAccountsByType("com.google");
					
					if(accounts.length <= 0){
						Toast.makeText(getApplicationContext(), "Ko có tài khoản google.thêm tài khoản!!!", Toast.LENGTH_LONG);
						finish();
					}
					
				}catch(Exception ex){
					
					Toast.makeText(getApplicationContext(), "loi"+ex.toString(), Toast.LENGTH_LONG);
					
				}					
				///end check account
				//AlertDialogManager alert = new AlertDialogManager();		
				//GCMRegistrar.unregister(getApplicationContext());
				boolean resultregister = RegisterServerPushnotification();				
				Log.e("aaaaaaaaaaaaaaaaaaaaaaaa", "congtt tets log");
				
				if(resultregister == true){
					Toast.makeText(getApplicationContext(), "Register to server ok!", Toast.LENGTH_SHORT);
					
				}else{
					Toast.makeText(getApplicationContext(), "Register to server false!", Toast.LENGTH_SHORT);
				}
				/*end push notification*/
			}
		}
		
		/**/
		
		

		/*TEST*/
		
		
		//HandleServer.GetListStoreNearPosition("10.3435553","106.342455","500");
		//ConvertData.LoadDataSourcePostNew("10.3435553","106.342455","500");
		 
		 
		 
		 /* END TEST*/
		
		
		btnArroundMe = (ImageButton) findViewById(R.id.imageButtonArroundMe);
		btnArroundMe.setOnClickListener(new OnClickListener() {
		
			
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Toast.makeText(v.getContext(),"here armobile", 5).show();
				Intent iArMobile = new Intent();
				iArMobile.setComponent(new ComponentName(v.getContext(),ArLocation.class));
				startActivity(iArMobile);
			}
		});	
		
		btnFavorite = (ImageButton) findViewById(R.id.imageButtonFavourite);
		btnFavorite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent in = new Intent(v.getContext(),Favorite.class);
				startActivity(in);
			}
		});
		
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	
		switch (item.getItemId()) {
		case R.id.signup:
			Intent iSignup = new Intent(this, signup.class);
			startActivity(iSignup);
			break;
		case R.id.login:
			Intent iLogin = new Intent(this, login.class);
			startActivity(iLogin);
			break;
		case R.id.armobile:
			Intent iArmobile = new Intent(this, armobile.class);
			startActivity(iArmobile);
			break;
		case R.id.favorite:
			Intent iFavorite = new Intent(this, Favorite.class);
			startActivity(iFavorite);
			break;
		case R.id.favorcategories:
			Intent iFavorCategories = new Intent(this, FavorCategories.class);
			startActivity(iFavorCategories);
			break;
		}
		return true;
	}
	
	

/*push notification */
	
	private boolean RegisterServerPushnotification(){
		
		ConnectionDetector cd;
		
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		try{
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			AlertDialogManager alert = new AlertDialogManager();
			alert.showAlertDialog(getApplicationContext(),
					"Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return false;
		}
		}catch(Exception e){
			
			Log.e("Loi check connect internet on push", e.toString());
		}
		
		// Getting name, email from intent
		Intent i = getIntent();		
		final String name = "My Name";//i.getStringExtra("name");
		final String email = "My email";//i.getStringExtra("email");		
		
		GCMRegistrar.checkDevice(this);
		
		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
	
		try{
				GCMRegistrar.checkManifest(this);			
				registerReceiver(mHandleMessageReceiver, new IntentFilter(
						CommonUtilities.DISPLAY_MESSAGE_ACTION));
					
			}catch(Exception exc){
				Log.e("Loi check connect internet on push", exc.toString());
			}
		final String regId = GCMRegistrar.getRegistrationId(this);
		
		
		//GCMRegistrar.unregister(getApplicationContext());
		
		// Check if regid already presents
		if (regId.equals("")) {			
			// Registration is not present, register now with GCM	
			try{
				GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
			}catch(Exception ex){
				System.out.println("Loi" + ex.toString());
			}
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.	
				global.regID = regId;
				
				User user = new User(1, regId, "Name", "email", "regDate", 0, "0");
				boolean re = DBHandle.CreateDBAndTable();
				
				if(re== true){
					
					re = DBHandle.UserAdd(user);
					if(re==true)
						global.curUser = user;
				}
				Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
				return true;
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						ServerUtilities.register(context, name, email, regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}		
		return false;	
	}
	
	/**
	 * Receiving push messages
	 * */
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString("message");
			// Waking up mobile if it is sleeping
			WakeLocker.acquire(getApplicationContext());
			
			/**
			 * Take appropriate action on this message
			 * depending upon your app requirement
			 * For now i am just displaying it on the screen
			 * */
			
			// Showing received message
			//lblMessage.append(newMessage + "\n");			
			Toast.makeText(getApplicationContext(), "New Message from server congtt: " + newMessage, Toast.LENGTH_LONG).show();
			
			// Releasing wake lock
			WakeLocker.release();
		}
	};
	
	
	
	
	
	/*end push notification */
	
	
}
